/*
 * Copyright 2015 Pivotal Software, Inc..
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.joomtu.smarterlife.config;

import java.io.File;
import java.io.IOException;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.kernel.impl.util.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.neo4j.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.config.Neo4jConfiguration;
import org.springframework.data.neo4j.rest.SpringCypherRestGraphDatabase;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 *
 * @author huguobing
 */
@Configuration
public class Neo4jConfig {

    @Value("${neo4j.embeded:true}")
    private Boolean neo4jIsEmbeded;

    @Value("${neo4j.database.path:target/neo4j.db}")
    private String neo4jDatabasePath;

    @Value("${neo4j.database.deleted:true}")
    private Boolean neo4jDatabaseDeleted;

    @Value("${neo4j.url:http://localhost:7474/db/data}")
    private String neo4jUrl;

    @Value("${neo4j.username}")
    private String neo4jUsername;

    @Value("${neo4j.password}")
    private String neo4jPassword;

    @Configuration
    @EnableScheduling
    @EnableTransactionManagement
    @EnableNeo4jRepositories(basePackages = "com.joomtu.smarterlife.neo4j.repositories")
    public static class Neo4j extends Neo4jConfiguration {

        public Neo4j() {
            setBasePackage("com.joomtu.smarterlife.neo4j.domain");
        }
    }

    @Bean(destroyMethod = "shutdown")
    public GraphDatabaseService graphDatabaseService() throws IOException {
        if (this.neo4jIsEmbeded) {
            if (this.neo4jDatabaseDeleted) {
                FileUtils.deleteRecursively(new File(this.neo4jDatabasePath));
            }
            return new GraphDatabaseFactory().newEmbeddedDatabase(this.neo4jDatabasePath);
        } else {
            return new SpringCypherRestGraphDatabase(this.neo4jUrl, this.neo4jUsername, this.neo4jPassword);
        }
    }

}
